<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table'

import { ref, inject } from 'vue'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { Button, Input } from 'ant-design-vue'
import { getProductTaskList } from '#/api/productTask'

interface RowType {
  [key: string]: any
}

const emit = defineEmits(['shareData'])
const modalApi = inject('modalApi')

const selectedRows = ref<RowType[]>([])
const quickSearch = ref('')

const gridOptions: VxeGridProps<RowType> = {
  border: true,
  checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  rowConfig: {
    useKey: true,
    keyField: 'product_task_id',
  },
  columnConfig: {
    useKey: true,
  },
  columns: [
    { type: 'checkbox', width: 60 },
    { field: 'product_task_sn', title: '生产任务单号', width: 150 },
    { field: 'product_name', title: '产品名称', width: 150 },
    { field: 'product_num', title: '产品数量', width: 100 },
    { field: 'created_at', title: '创建时间', width: 160 },
    { field: 'created.realname', title: '创建人', width: 120 },
  ],
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  pagerConfig: {
    pageSize: 10,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        const res = await getProductTaskList({
          page: page.currentPage,
          limit: page.pageSize,
          quick_search: quickSearch.value,
        })

        return {
          items: res.list,
          total: res.total,
        }
      },
    },
    sort: true,
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
}

const doSearch = () => {
  gridApi.query()
}

const handleSelect = () => {
  const selectedRecords = gridApi.grid.getCheckboxRecords()
  if (selectedRecords && selectedRecords.length > 0) {
    emit('shareData', { list: selectedRecords })
    modalApi.close()
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions,
  gridEvents: {
    checkboxChange: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
    checkboxAll: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    }
  },
})
</script>

<template>
  <div class="p-4">
    <div class="flex justify-between items-center mb-4">
      <h2 class="text-lg font-medium">选择生产任务单</h2>
      <div class="flex items-center">
        <Input
          v-model:value="quickSearch"
          placeholder="输入关键字搜索"
          class="mr-2"
          @change="doSearch"
        />
        <Button type="primary" @click="handleSelect" :disabled="selectedRows.length === 0">
          选择
        </Button>
      </div>
    </div>
    <Grid />
  </div>
</template>
